﻿using AutoMapper;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.VModel;
using IOA.MES.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IOA.MES.Business
{
    /// <summary>
    /// QTime配置（错误代码：109001）
    /// </summary>
    public class QTimeMgr
    {
        private MESContext mesDb = new MESContext("MES");

        /// <summary>
        /// 编辑
        /// </summary>
        /// <returns></returns>
        public VQTime Edit(VQTime model)
        {

            if (model.PkId <= 0)
            {
                model.CreateTime = DateTime.Now;
                model.ModifyBy = 0;
                var entity = Mapper.Map<DataAccess.Entity.QTime>(model);
                mesDb.QTimes.Add(entity);
                mesDb.SaveChanges();

                model = Mapper.Map<VQTime>(entity);
            }
            else
            {
                var entity = mesDb.QTimes.FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
                if (entity == null)
                {
                    throw new MultiLanBizException(109001);// "待编辑的记录不存在或已被删除，无法编辑");
                }
                entity.OrderNo = model.OrderNo;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
                mesDb.SaveChanges();

                model = Mapper.Map<VQTime>(entity);
            }
            return model;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <returns></returns>
        public VQTime Get(string orderNo)
        {
            VQTime model = null;
            var entity = mesDb.QTimes.FirstOrDefault(_ => _.Valid && _.OrderNo.Equals(orderNo));
            if (entity == null)
            {
                model = new VQTime();
            }
            else
            {
                model = new VQTime
                {
                    PkId = entity.PkId,
                    OrderNo = !string.IsNullOrEmpty(entity.OrderNo) ? entity.OrderNo.Trim() : string.Empty
                };
            }
            return model;
        }
    }
}
